package com.moss.common.core;

import com.github.pagehelper.PageHelper;
import com.moss.common.exception.ServiceException;
import com.moss.common.util.DateTimeUtil;
import com.moss.common.util.TokenUtil;
import org.apache.commons.lang3.StringUtils;
import org.hibernate.validator.internal.util.StringHelper;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;

/**
 * @author gxcc3
 * @date 2024/8/1 23:13
 */
public class BaseController {


    public String getUserId(){
        RequestAttributes attributes = RequestContextHolder.getRequestAttributes();
        ServletRequestAttributes requestAttributes = (ServletRequestAttributes) attributes;
        if (requestAttributes == null){
            throw new ServiceException("请求异常，解析token失败");
        }
        HttpServletRequest request = requestAttributes.getRequest();
        String token = request.getHeader("token");
        return TokenUtil.getUserId(token);
    }

    public String getOrgId(){
        RequestAttributes attributes = RequestContextHolder.getRequestAttributes();
        ServletRequestAttributes requestAttributes = (ServletRequestAttributes) attributes;
        if (requestAttributes == null){
            throw new ServiceException("请求异常，解析token失败");
        }
        HttpServletRequest request = requestAttributes.getRequest();
        String token = request.getHeader("token");
        return TokenUtil.getOrgId(token);
    }


    public void startPage(){
        RequestAttributes attributes = RequestContextHolder.getRequestAttributes();
        ServletRequestAttributes requestAttributes = (ServletRequestAttributes) attributes;
        if (requestAttributes == null){
            throw new ServiceException("请求异常，分页失败");
        }
        HttpServletRequest request = requestAttributes.getRequest();
        String pageNum = request.getParameter("pageNum");
        String pageSize = request.getParameter("pageSize");
        //如果有分页参数，启用分页，不存在则不启用
        //分页参数除非特殊情况，否则其他情况都需要加
        if (StringUtils.isEmpty(pageNum) || StringUtils.isEmpty(pageSize)){
            return;
        }
        PageHelper.startPage(Integer.parseInt(pageNum), Integer.parseInt(pageSize));
    }
}
